import React from "react";

export default class LoadCss extends React.Component {
  state = { stylePath: "" };

  handleButtonClick = (type) => {
    return () => {
      this.setState({ stylePath: type }, () => {
        const { stylePath } = this.state;
        const href = stylePath === 1 ? "/css/a.css" : "/css/b.css";
        this.loadCss(href);
        if (href === "/css/a.css") {
          this.removeCss("/css/b.css");
        } else {
          this.removeCss("/css/a.css");
        }
      });
    };
  };

  /**
   * 删除 link 文件
   * @param href
   */
  removeCss(href) {
    let links = document.getElementsByTagName("link");
    for (let i = 0; i < links.length; i++) {
      let _href = links[i].href;
      if (links[i] && _href && _href.indexOf(href) !== -1) {
        links[i].parentNode.removeChild(links[i]);
      }
    }
  }

  /**
   * 加载 link 文件
   * @param href
   */
  loadCss(href) {
    let addSign = true;
    let links = document.getElementsByTagName("link");
    for (let i = 0; i < links.length; i++) {
      if (links[i] && links[i].href && links[i].href.indexOf(href) !== -1) {
        addSign = false;
      }
    }
    if (addSign) {
      var $link = document.createElement("link");
      $link.setAttribute("rel", "stylesheet");
      $link.setAttribute("type", "text/css");
      $link.setAttribute("href", href);
      document.getElementsByTagName("head")[0].appendChild($link);
    }
  }

  render() {
    return (
      <div className="test">
        <link rel="stylesheet" type="text/css" href={this.state.stylePath} />
        <button type="button" onClick={this.handleButtonClick(1)}>
          加载a.css
        </button>
        <button type="button" onClick={this.handleButtonClick(2)}>
          加载b.css
        </button>
        <button onClick={() => this.props.history.push("/home")}>
          跳转首页
        </button>
      </div>
    );
  }
}
